<template>
  <div>
    <v-form v-model="valid" ref="yun9">
      <v-text-field
        v-model="brand.name"
        :counter="10"
        label="Name"
        required
      ></v-text-field>
      <v-text-field
        v-model="brand.letter"
        label="首字母"
        required
      ></v-text-field>

      <v-cascader
        url="/item/category/list"
        multiple
        required
        v-model="brand.categories"
        label="请选择商品分类"/>
    </v-form>

    <v-layout row>
      <v-flex xs3>
        <span style="font-size: 16px; color: #444">品牌LOGO：</span>
      </v-flex>
      <v-flex>
        <v-upload
          v-model="brand.image"
          url="/upload/image"
          :multiple="false"
          :pic-width="250"
          :pic-height="90"
        />
      </v-flex>
    </v-layout>

    <v-btn color="warning" @click="clear">重置</v-btn>
    <v-btn color="info" @click="submit">提交</v-btn>
  </div>
</template>

<script>
  export default {
    name: "my-brand-form",
    props: {
      oldBrand: {
        type: Object,
        default: {}
      },
      edit:{
        type:Boolean,
        default:false
      }
    },
    data() {
      return {
        valid: false,
        brand: {
          name: "",
          letter: "",
          categories: [],
          image: ""
        }
      }
    },
    methods: {
      clear() {

        console.log(this)

        //找打当前对象索绑定的所有关系并从中找到对应的绑定，调其方法
        this.$refs.yun9.reset();

        //关于数组对象的清空有bug
        this.brand.categories = [];
      },
      submit() {
        if (this.$refs.yun9.validate()) {

          //结构brand对象取出，categories数组
          let {categories, ...others} = this.brand;

          //迭代数组取出数组中对象的id，重新生成新的数组
          categories = categories.map(category => category.id);

          //把数组转为字符串并作为属性的值赋值给cids
          others.cids = categories.join();

          this.$http({
            method: this.edit ? 'put' : 'post', // 动态判断是POST还是PUT
            url: '/item/brand',
            //axois会把查询参数自动转为json
            data: this.$qs.stringify(others)
          }).then(resp => {
              this.$message.success(this.edit?"修改":"新增"+"品牌成功");


              this.brand = {}
              //关闭新增窗口
              this.$emit("close")
            }).catch(resp => {
            this.$message.error(this.edit?"修改":"新增"+"品牌失败")
          })
        } else {
          this.$message.error("表单校验未通过");
        }


      }
    },
    watch:{
      oldBrand:{
        deep:true,
        handler(){
          this.brand = this.oldBrand;
        }
      }
    }
  }
</script>

<style scoped>

</style>
